const express = require('express');
const { authenticateToken, requirePermissions } = require('../middleware/auth');
const User = require('../models/User');
const Product = require('../models/Product');
const Order = require('../models/Order');

const router = express.Router();

// 所有dashboard路由都需要认证
router.use(authenticateToken);

/**
 * 获取Dashboard概览数据
 * GET /api/dashboard/overview
 */
router.get('/overview', requirePermissions(['dashboard:view']), async (req, res) => {
  try {
    // 并行获取各种统计数据
    const [userStats, orderStats, productStats] = await Promise.all([
      User.getStats(),
      Order.getStats(),
      Product.getStats()
    ]);

    const overview = {
      // 今日数据
      today: {
        newUsers: userStats.today,
        orders: orderStats.today,
        sales: orderStats.todaySales
      },
      // 昨日数据
      yesterday: {
        newUsers: userStats.yesterday,
        orders: orderStats.yesterday,
        sales: orderStats.yesterdaySales
      },
      // 累计数据
      total: {
        users: userStats.total,
        orders: orderStats.total,
        sales: orderStats.totalSales,
        products: productStats.total
      },
      // 商品统计
      products: {
        total: productStats.total,
        active: productStats.active,
        lowStock: productStats.lowStock
      }
    };

    res.success(overview, '获取概览数据成功');

  } catch (error) {
    console.error('获取概览数据失败:', error);
    res.error('获取概览数据失败', 500, error.message);
  }
});

/**
 * 获取待办事项
 * GET /api/dashboard/pending-tasks
 */
router.get('/pending-tasks', requirePermissions(['dashboard:view']), async (req, res) => {
  try {
    // 获取待处理订单统计
    const pendingOrders = await Order.getPendingStats();
    
    // 获取库存预警商品
    const lowStockProducts = await Product.getLowStockProducts(5);

    const tasks = {
      // 待处理订单
      pendingOrders: {
        pendingPayment: pendingOrders.pending_payment || 0,
        processing: pendingOrders.processing || 0,
        shipped: pendingOrders.shipped || 0,
        total: (pendingOrders.pending_payment || 0) + 
               (pendingOrders.processing || 0) + 
               (pendingOrders.shipped || 0)
      },
      // 库存预警
      lowStock: {
        count: lowStockProducts.length,
        products: lowStockProducts.slice(0, 10) // 只返回前10个
      }
    };

    res.success(tasks, '获取待办事项成功');

  } catch (error) {
    console.error('获取待办事项失败:', error);
    res.error('获取待办事项失败', 500, error.message);
  }
});

/**
 * 获取销售趋势数据
 * GET /api/dashboard/sales-trend
 */
router.get('/sales-trend', requirePermissions(['dashboard:view']), async (req, res) => {
  try {
    const { days = 7 } = req.query;
    
    // 获取销售趋势数据
    const salesTrend = await Order.getSalesTrend();
    
    // 补全缺失的日期数据
    const today = new Date();
    const trendData = [];
    
    for (let i = days - 1; i >= 0; i--) {
      const date = new Date(today);
      date.setDate(date.getDate() - i);
      const dateStr = date.toISOString().split('T')[0];
      
      const existingData = salesTrend.find(item => 
        item.date && item.date.toISOString().split('T')[0] === dateStr
      );
      
      trendData.push({
        date: dateStr,
        orderCount: existingData ? existingData.orderCount : 0,
        salesAmount: existingData ? existingData.salesAmount : 0
      });
    }

    res.success(trendData, '获取销售趋势成功');

  } catch (error) {
    console.error('获取销售趋势失败:', error);
    res.error('获取销售趋势失败', 500, error.message);
  }
});

/**
 * 获取用户增长趋势
 * GET /api/dashboard/user-growth
 */
router.get('/user-growth', requirePermissions(['dashboard:view']), async (req, res) => {
  try {
    const { days = 7 } = req.query;
    
    // 获取用户增长趋势数据
    const userGrowth = await User.getGrowthTrend();
    
    // 补全缺失的日期数据
    const today = new Date();
    const trendData = [];
    
    for (let i = days - 1; i >= 0; i--) {
      const date = new Date(today);
      date.setDate(date.getDate() - i);
      const dateStr = date.toISOString().split('T')[0];
      
      const existingData = userGrowth.find(item => 
        item.date && item.date.toISOString().split('T')[0] === dateStr
      );
      
      trendData.push({
        date: dateStr,
        count: existingData ? existingData.count : 0
      });
    }

    res.success(trendData, '获取用户增长趋势成功');

  } catch (error) {
    console.error('获取用户增长趋势失败:', error);
    res.error('获取用户增长趋势失败', 500, error.message);
  }
});

/**
 * 获取快捷操作数据
 * GET /api/dashboard/quick-actions
 */
router.get('/quick-actions', requirePermissions(['dashboard:view']), async (req, res) => {
  try {
    // 这里可以根据用户权限返回不同的快捷操作
    const actions = [
      {
        id: 'add-product',
        title: '发布新商品',
        description: '添加新的珠宝商品',
        icon: 'plus',
        route: '/products/create',
        permission: 'product:create'
      },
      {
        id: 'view-orders',
        title: '查看订单',
        description: '管理客户订单',
        icon: 'shopping-cart',
        route: '/orders',
        permission: 'order:view'
      },
      {
        id: 'manage-users',
        title: '用户管理',
        description: '查看和管理用户',
        icon: 'users',
        route: '/users',
        permission: 'user:view'
      },
      {
        id: 'inventory-alert',
        title: '库存预警',
        description: '查看库存不足的商品',
        icon: 'alert-triangle',
        route: '/products?filter=low-stock',
        permission: 'product:view'
      },
      {
        id: 'sales-report',
        title: '销售报表',
        description: '查看详细销售数据',
        icon: 'bar-chart',
        route: '/reports/sales',
        permission: 'report:view'
      },
      {
        id: 'customer-service',
        title: '处理售后',
        description: '处理客户售后问题',
        icon: 'headphones',
        route: '/service',
        permission: 'service:view'
      }
    ];

    // 根据用户权限过滤快捷操作
    // 这里简化处理，实际应该根据用户权限过滤
    res.success(actions, '获取快捷操作成功');

  } catch (error) {
    console.error('获取快捷操作失败:', error);
    res.error('获取快捷操作失败', 500, error.message);
  }
});

/**
 * 获取最近活动
 * GET /api/dashboard/recent-activities
 */
router.get('/recent-activities', requirePermissions(['dashboard:view']), async (req, res) => {
  try {
    const { limit = 10 } = req.query;
    
    // 获取最近的订单活动
    const recentOrders = await Order.getList({
      page: 1,
      pageSize: limit,
      sort: 'created_at',
      order: 'DESC'
    });

    const activities = recentOrders.orders.map(order => ({
      id: `order-${order.id}`,
      type: 'order',
      title: `新订单 #${order.order_number}`,
      description: `用户 ${order.user_nickname} 下单，金额 ¥${order.total_amount}`,
      time: order.created_at,
      status: order.status
    }));

    res.success(activities, '获取最近活动成功');

  } catch (error) {
    console.error('获取最近活动失败:', error);
    res.error('获取最近活动失败', 500, error.message);
  }
});

module.exports = router;
